/**
 * 项目信息
 */
define(function (require, exports, module) {
    var angular = require('angular');
    var $ = require('jquery');
    var ui = require('ui');
    var dialog = require("dialog");
    var areabox = require('areabox');
    var util = require('util');
    require("jqtree");

    angular.module('projectInfo', [])
        .service('commonservice', ["$http", function ($http) {
            var service = {
                getCities: function (data, search) {
                    search = (search || '') + '&rnd=' + (new Date()).getTime();
                    data = data || {}
                    data['params'] = data['params'] || {};
                    data['params']['NEED_TOKEN'] = false;
                    return $http.get('/api/index.php?r=common/get-all-province' + search, data);
                },
                queryAllOrganizations: function (data, search) {
                    search = (search || '') + '&rnd=' + (new Date()).getTime();
                    data = data || {};
                    data['params'] = data['params'] || {};
                    data['params']['NEED_TOKEN'] = false;
                    return $http.get('/api/index.php?r=usermanage/organization/query-all-organizations' + search, data);
                },
                saveProjectInfo: function (data, search) {
                    search = (search || '') + '&rnd=' + (new Date()).getTime();
                    data = data || {};
                    data['NEED_TOKEN'] = false;
                    return $http.post('/api/index.php?r=project/project/update-project-info' + search, data)
                },
                getProjInfo: function (data, search) {
                    search = (search || '') + '&rnd=' + (new Date()).getTime();
                    data = data || {};
                    data['params'] = data['params'] || {};
                    data['params']['NEED_TOKEN'] = false;
                    return $http.get('/api/index.php?r=project/project/get-project-info' + search, data);
                },
                cancelBind: function (data, search) {
                    search = (search || '') + '&rnd=' + (new Date()).getTime();
                    data = data || {};
                    data['NEED_TOKEN'] = false;
                    return $http.post('/api/index.php?r=project/auth/check-has-opp-data-by-project-id' + search, data);
                },
                checkCanBind: function (data, search) {
                    search = (search || '') + '&rnd=' + (new Date()).getTime();
                    data = data || {};
                    data['params'] = data['params'] || {};
                    data['params']['NEED_TOKEN'] = false;
                    return $http.get('/api/index.php?r=project/auth/check-binding-erp' + search, data)
                },
                getErpProjectsList: function (data, search) {
                    search = (search || '') + '&rnd=' + (new Date()).getTime();
                    data = data || {};
                    data['params'] = data['params'] || {};
                    data['params']['NEED_TOKEN'] = false;
                    return $http.get('/api/index.php?r=common/erp-interface/get-erp-project-list' + search, data)
                },
                getErpCompanies: function (data, search) {
                    search = (search || '') + '&rnd=' + (new Date()).getTime();
                    data = data || {};
                    data['params'] = data['params'] || {};
                    data['params']['NEED_TOKEN'] = false;
                    return $http.get('/api/index.php?r=usermanage/organization/query-all-erp-companies' + search, data)
                },
                checkProjNameCanUse: function (data, search) {
                    search = (search || '') + '&rnd=' + (new Date()).getTime();
                    data = data || {};
                    data['params'] = data['params'] || {};
                    data['params']['NEED_TOKEN'] = false;
                    return $http.get('/api/index.php?r=project/project/check-project-name-exist' + search, data)
                }
            };
            return service;

        }])
        .directive('projNameAllow',
        ['commonservice', function (commonservice) {
            return {
                require: 'ngModel',
                link: function (scope, element, attrs, ngModel) {
                    function setAsAvailable(bool) {
                        ngModel.$setValidity('projNameAllow', bool);
                        //$(element).blur().focus();
                    }


                    function checkProjAction(value) {
                        if (!value || value.length == 0 || value == scope.curProjInfo.ProjName) {
                            return;
                        }

                        var queryString = "&projectName=" + value + '&filterId=' + scope.curProjectId+'&organizationId='+scope.curProjInfo.BUGUID+'&parentGUID='+scope.curProjInfo.parentGUID;
                        commonservice.checkProjNameCanUse({}, queryString).then(function (res) {
                            if (res && res.data.retCode == 0) {
                                ischecking = true;
                                setAsAvailable(!res.data.data);
                            }
                        });

                        return value;
                    }

                    $(element).on('blur',function(){
                        checkProjAction(ngModel.$modelValue)
                    });
                    //ngModel.$parsers.push(_.debounce(checkProjAction, 500));
                    //ngModel.$parsers.push(checkProjAction);
                }
            }
        }])
        .controller('projectInfoCtl', ['$rootScope', '$scope', '$q', '$location', 'commonservice', function ($rootScope, $scope, $q, $location, commonservice) {
            var address = $('#address');

            var bindErpList = [];

            function fixedData(data) {
                angular.forEach(data, function (item) {
                    item.children = item.childNodes;
                    fixedData(item.childNodes);
                });
                return data;
            }

            //初始化区域选择控件

            areabox.init(address, {
                title: '选择省份',
                asyncDataApi: {
                    province: '/api/index.php?r=common/region/get-all-province',
                    city: '/api/index.php?r=common/region/get-all-city-by-province-id',
                    district: '/api/index.php?r=common/region/get-all-area-by-city-id'
                },
                showRange: {start: 1, end: 3},
                placement: "bottom",
                callBack: function (dom) {
                    $scope.address = dom.val();
                    $scope.$apply();
                }
            });
            //所属公司
            commonservice.queryAllOrganizations().then(function (res) {
                if (res && res.data && res.data.retCode == 0) {
                    $tree.tree({
                        data: fixedData(res.data.data),
                        dragAndDrop: false,
                        useContextMenu: false,
                        autoOpen: 0, //展开级别
                        onCreateLi: function (node, $li) {
                        },
                        //是否可以移动
                        onCanMove: function (node) {
                            return false;
                        },
                        //是否可以移动到
                        onCanMoveTo: function (moved_node, target_node, position) {
                            //只能在同级节点中移动
                            return false;
                        },
                        //移动句柄
                        onIsMoveHandle: function ($ele) {
                            return false;
                        }
                    }).on(
                        'tree.click',
                        function (event) {
                            var node = event.node;
                            $scope.belongsCompany = node;
                            $scope.isTreeCollapse = false;
                            $('input[name=projectName]').blur();
                            $scope.$apply();
                        }
                    );
                }
            });


            var $tree = $("#tree_table");
            $scope.isTreeCollapse = false;

            $scope.toggleTreeCombo = function () {
                $scope.isTreeCollapse = !$scope.isTreeCollapse;
                $(window).on('click', function (event) {
                    var target = $(event.target);
                    if ($tree.parent().has(target).length < 1) {
                        $scope.isTreeCollapse = false;
                    }
                    $scope.$apply();
                });
            };

            var $orgProjTree = null, $orgTree = null, rdata = [];

            $scope.dialogHasShow = false;

            $scope.beforeShowERPProject = function (dialog, dialogScope) {
                $scope.dialogHasShow = true;
                if ($scope.canEdit == 0) {
                    return false;
                }
                var data = {};
                var erpProjId = '';
                if ($scope.bindErpList && $scope.bindErpList.length > 0 && $scope.bindErpList[0].Erp_ProjectGUID) {
                    erpProjId = $scope.bindErpList[0].Erp_ProjectGUID;
                }
                commonservice.checkCanBind(data, '&projectId=' + $scope.curProjectId+"&erpProjId="+erpProjId).then(function (res) {
                    if (res.data.retCode == 0) {
                        if(res.data.data.erpId){
                            $scope.select_org_id = res.data.data.erpId;
                        }
                        dialog.showModal();
                        $scope.dialogHasShow = false;
                        $scope.showERPProject();
                    }
                });
                return false;
            };


            $scope.showERPCompany = function () {
                var data = {}, deferred = $q.defer();

                commonservice.getErpCompanies(data).then(function (res) {
                    rdata = res.data.data;
                    if (res.data.retCode == 0) {
                        //左侧组织名称
                        $orgTree = $('#org_name_tree');
                        $orgTree.tree("destroy");
                        $orgTree.tree({
                            data: rdata,
                            dragAndDrop: false,
                            useContextMenu: false,
                            autoOpen: 0, //展开级别
                            onCreateLi: function (node, $li) {
                                var id = node.id;
                                $li.find(".jqtree-element").attr('id', node.id);
                            },
                            //是否可以移动
                            onCanMove: function (node) {
                                return false;
                            },
                            //是否可以移动到
                            onCanMoveTo: function (moved_node, target_node, position) {
                                //只能在同级节点中移动
                                return false;
                            },
                            //移动句柄
                            onIsMoveHandle: function ($ele) {
                                return false;
                            }
                        }).on('tree.click', function (event) {
                            var node = event.node, projList;
                            event.preventDefault();
                            var node = event.node;
                            var checked = getCheckedErpList();
                            if (checked.length > 0) {
                                dialog({
                                    title: '提示',
                                    fixed: true,
                                    content: "<h4>不允许同时绑定不同组织下的项目！</h4>",
                                    width: 350,
                                    okValue: '确定',
                                    cancelDisplay: false,
                                    ok: function () {
                                    },
                                    cancel: function () {
                                    }
                                }).showModal();
                                return;
                            } else {
                                $orgTree.find('.jqtree-selected').removeClass('jqtree-selected');
                                $("#" + node.id).closest('li').addClass('jqtree-selected');
                                $scope.select_org_id = node.id;
                                getErpProjListReq(node.id);
                            }
                        });
                        deferred.resolve(res.data)
                    }
                });

                return deferred.promise;

            };

            function getCheckedErpList() {
                return $orgProjTree.find("input[type=checkbox]:checked");
            }

            function checkSelectedValid(chk) {
                //不允许同时绑定ERP的两个项目
                var checked = getCheckedErpList(), flag = false;
                checked.each(function () {
                    var cur_ckbox = $(this);
                    var cur_id = $(chk.closest("li.has-child").find('input.has-child')[0]).attr('id');
                    if (cur_id != $(cur_ckbox.closest("li.has-child").find('input.has-child')[0]).attr('id')||(chk.attr('level')==2&&cur_id!=chk.attr('id'))) {
                        flag = true;
                    }
                });
                return flag
            }

            function getErpProjListReq(id) {

                commonservice.getErpProjectsList({}, '&id=' + id + '&projectId=' + $scope.curProjectId).then(function (res) {
                    if (res.data.retCode == 0) {
                        //右侧项目列表
                        $orgProjTree = $('#erp_proj_tree');
                        $orgProjTree.tree("destroy");
                        $orgProjTree.tree({
                            data: res.data.data,
                            dragAndDrop: false,
                            useContextMenu: false,
                            autoOpen: 0, //展开级别
                            onCreateLi: function (node, $li) {
                                var id = node.id,level = node.Level,hasChildClass = node.children.length > 0 ? 'has-child' : '';
                                $li.addClass(hasChildClass).find(".jqtree-element").append("<span class='projcode'>" + node.ProjCode + "</span>");
                                level == 3 ? $li.find('.jqtree-title').css({'margin-left':'40px'}):'';
                                $li.find(".jqtree-element").before("<span class='checkbox proj_tree'><input id='" + id +"' level='" + level
                                    + "' class='" + hasChildClass + "' type='checkbox' value=''><label for='" + id + "'>&nbsp;</label></span>");
                            },
                            //是否可以移动
                            onCanMove: function (node) {
                                return false;
                            },
                            //是否可以移动到
                            onCanMoveTo: function (moved_node, target_node, position) {
                                //只能在同级节点中移动
                                return false;
                            },
                            //移动句柄
                            onIsMoveHandle: function ($ele) {
                                return false;
                            }
                        }).on(
                            'tree.click',
                            function (event) {
                                event.preventDefault();
                                var node = event.node, checkbox = $('#' + node.id), isCheckedAllSub;
                                if (!checkbox.prop("checked") && checkSelectedValid(checkbox)) {
                                    dialog({
                                        title: '提示',
                                        fixed: true,
                                        content: "<h4>不允许同时绑定ERP的两个项目！</h4>",
                                        width: 350,
                                        okValue: '确定',
                                        cancelDisplay: false,
                                        ok: function () {
                                        },
                                        cancel: function () {
                                        }
                                    }).showModal();
                                    return;
                                }

                                if (checkbox.prop("checked")) {
                                    checkbox.prop("checked", false);
                                    node.checked = false;
                                } else {
                                    checkbox.prop("checked", "checked");
                                    node.checked = true;
                                }
                                //父级节点则子节点全部勾选
                                if (node.children.length > 0) {
                                    checkbox.closest(".jqtree-folder").find("input[type=checkbox]").prop("checked", checkbox.prop("checked"));
                                    _.each(node.children, function (item) {
                                        item.checked = false;
                                    })
                                }
                                //子节点全部勾选则父节点勾选
                                isCheckedAllSub = _.every(node.parent.children, function (item) {
                                    return item.checked == true;
                                })
                                if (isCheckedAllSub) {
                                    $('#' + node.parent.id).prop("checked", "checked");
                                    node.parent.checked = true;
                                }

                                if (!checkbox.prop("checked")) {
                                    $('#' + node.parent.id).prop("checked", false);
                                    node.parent.checked = false;
                                }
                            }
                        );
                        //选中回现  初始已有绑定的项目取消绑定状态被置为delete的不用勾选上
                        _.each($scope.bindErpList, function (item) {
                            if(item.type!='delete'){
                                $('#' + item.Erp_ProjectGUID).prop("checked", "checked");
                            }
                        });
                    }
                })

            }


            $scope.showERPProject = function (dialog, dialogScope) {
                $scope.showERPCompany().then(function (res) {
                        var data = {}, companyId;
                        if ($scope.select_org_id) {
                            companyId = $scope.select_org_id;
                        } else {
                            if ($scope.bindErpList && $scope.bindErpList.length > 0 && $scope.bindErpList[0].erpId) {
                                companyId = $scope.bindErpList[0].erpId;
                            } else {
                                companyId = res.data[0] && res.data[0].id;
                            }
                            $scope.select_org_id = companyId;
                        }
                        if(!companyId){
                            return;
                        }
                        var node = $orgTree.tree('getNodeById', companyId);
                        node.checked = true;
                        $("#" + node.id).closest('li').addClass('jqtree-selected');
                        getErpProjListReq(companyId);
                    }
                )
            };

            //绑定ERP项目添加到列表，点击保存的时候提交数据
            $scope.bindERPProject = function () {
                var selectedNodes = getCheckedErpList(), nodesList = [];
                _.each(selectedNodes, function (chk) {
                    var node = $orgProjTree.tree('getNodeById', $(chk).attr('id'));
                    if (node.children.length < 1) {
                        nodesList.push({
                            Erp_ProjectName: node.name,
                            Erp_ProjectGUID: node.ProjGUID,
                            type: 'add',
                            erpId:$scope.select_org_id,
                            Erp_ParentProjectGUID: node.parent?node.parent.ProjGUID:''
                        })
                    }
                });
                _.each(nodesList, function (item) {
                    var index = _.indexOf(_.pluck($scope.bindErpList, 'Erp_ProjectGUID'), item.Erp_ProjectGUID);
                    if (index < 0) {//新勾选的
                        $scope.bindErpList.push(item);
                    } else if ($scope.bindErpList[index].type == 'delete') {//先在绑定列表取消勾选，之后又在弹出层内勾选
                        $scope.bindErpList[index].type = 'init';
                    }
                });

                //在弹窗层里取消的绑定项目处理
                $scope.bindErpList =  _.filter($scope.bindErpList,function(item){
                    var index = _.indexOf(_.pluck(nodesList, 'Erp_ProjectGUID'), item.Erp_ProjectGUID);
                    if (index < 0 && item.type == 'init') {//在弹出层取消初始列表里的绑定项目
                        item.type = 'delete';
                        item.DefaultProject = 0;
                        return true;
                    } else if (index < 0 && item.type == 'add') {
                        return false;
                    }
                    return true;
                });
                //新添加的ERP项目设置第一个为默认
                setDefaultBindErpProj();

            };

            function setDefaultBindErpProj() {
                var hasDefault = _.some($scope.bindErpList, function (item) {
                    return item.type != 'delete' && item.DefaultProject == 1;
                });

                if (!hasDefault && $scope.bindErpList.length > 0) {
                    var defaultProj = _.find($scope.bindErpList,function (item) {
                        return item.type != 'delete' && item.DefaultProject !=1;
                    });
                    if(defaultProj){
                        defaultProj.DefaultProject = 1;
                        $scope.defaultErpProjectId = defaultProj.Erp_ProjectGUID;
                    }
                }
            }


            //取消绑定，先发请求看是否可以取消，可以则从列表删除，点击保存时发送数据
            $scope.cancelBind = function (item) {
                var data = {projectId: $scope.curProjectId};
                if ($scope.canEdit == 0) {
                    return;
                }
                //新添加过来的不用检查，可以直接取消
                if (item.type !== 'add') {
                    commonservice.cancelBind(data).then(function (res) {
                        if (res.data.retCode == 0) {
                            item.type = 'delete';
                            item.DefaultProject = 0;
                            setDefaultBindErpProj();
                        }
                    });
                    //取消新增加的
                } else {
                    $scope.bindErpList = _.filter($scope.bindErpList, function (listItem) {
                        return listItem.Erp_ProjectGUID != item.Erp_ProjectGUID;
                    });
                    setDefaultBindErpProj();
                }

            };
            $scope.defaultErpProjectId = '';

            //设为默认
            $scope.setDefault = function (item) {
                if ($scope.canEdit == 0) {
                    return;
                }
                _.each($scope.bindErpList, function (item) {
                    if (item.DefaultProject == 1) {
                        item.DefaultProject = 0;
                    }
                });
                item.DefaultProject = 1;
                $scope.defaultErpProjectId = item.Erp_ProjectGUID;
            };

            //保存数据
            $scope.saveData = function (formvalid) {
                var erpProjList = [];

                if (!formvalid ) {
                    return;
                }
                _.each($scope.bindErpList, function (item) {
                    item.ProjectGUID = $scope.curProjectId;
                    if (item.type != 'init') {
                        erpProjList.push(_.pick(item, 'Erp_ParentProjectGUID', 'Erp_ProjectGUID', 'p_Project2ErpProjectId', 'Erp_ProjectName', 'ProjectGUID', 'type', 'DefaultProject'));
                    }
                });
                var data = {
                    info: {
                        ProjName: $scope.projectName,
                        BUName: $scope.belongsCompany.name,
                        BUGUID: $scope.belongsCompany.id,
                        myscrm_ProvinceId: address.attr('province'),
                        myscrm_CityId: address.attr('city'),
                        p_projectId: $scope.curProjectId,
                        parentGUID:$scope.curProjInfo.parentGUID||'null',
                        myscrm_AreaId: address.attr('district')
                    },
                    erpProject: erpProjList
                };
                if ($scope.defaultErpProjectId) {
                    data.defaultErpProjectId = $scope.defaultErpProjectId;
                }
                commonservice.saveProjectInfo(data).then(function (res) {
                    if (res.data.retCode == 0) {
                        ui.showSucTip('操作成功！');
                        setTimeout(function(){
                            getProjInfoByProjId($scope.curProjectId);
                        },1000);
                    }
                });
            };
            /**
             * 获取项目信息
             * @param curProjectId
             */
            function getProjInfoByProjId(curProjectId) {
                commonservice.getProjInfo({}, '&projectId=' + curProjectId)
                    .then(projInfoCallback)
            }

            function projInfoCallback(res){
                if (res.data && res.data.retCode == 0) {
                    var projInfo = res.data.data && res.data.data.info;
                    $scope.projectName = projInfo.ProjName;
                    $scope.curProjInfo = projInfo;
                    $scope.belongsCompany = {name: projInfo.BUName, id: projInfo.BUGUID};
                    $scope.bindErpList = _.each(res.data.data.erpProject, function (item) {
                        item.type = 'init'
                    });
                    var city = projInfo.provinceName + (projInfo.cityName ? '-' + projInfo.cityName + (projInfo.areaName ? '-' + projInfo.areaName : '') : '')
                    $('#address').val(city);
                    var addr = {
                        province: projInfo.myscrm_ProvinceId,
                        city: projInfo.myscrm_CityId,
                        district: projInfo.myscrm_AreaId
                    };
                    $scope.address = city;
                    $('#address').attr(addr);
                }
            }

            $scope.$on('changeCurProjectId', function (event, curProjectId,projInfoData) {
                if(projInfoData){
                    projInfoCallback(projInfoData)
                }else{
                    getProjInfoByProjId(curProjectId);
                }
                $scope.curProjectId = curProjectId;
            });

            $scope.$on('changeCanEdit', function (event, canEdit) {
                $scope.canEdit = canEdit;
                $scope.$applyAsync();
            });
            if ($scope.curProjectId) {
                getProjInfoByProjId($scope.curProjectId);
            }
        }])
});